<template>
  <view class="account-container">
    <!-- 顶部用户信息 -->
    <view class="user-info-section">
      <view class="user-avatar-wrapper">
        <image v-if="userInfo.avatar" class="user-avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <view v-else class="cu-avatar xl round bg-white user-avatar">
          <view class="iconfont icon-people text-gray icon"></view>
        </view>
      </view>
      <view class="user-info">
        <text class="user-phone">{{userInfo.name || userInfo.phone}}</text>
        <text class="user-phone-sub">{{userInfo.phone}}</text>
      </view>
      <view class="switch-account" @click="handleToLogin">
        <text>切换账号</text>
        <text class="iconfont icon-right"></text>
      </view>
    </view>

    <!-- 账户卡片 -->
    <view class="account-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.type"
        :class="['tab-item', {active: activeTab === tab.type}]"
        @click="activeTab = tab.type"
      >
        {{ tab.label }}
      </view>
    </view>

    <view class="main-content">
      <view class="account-card">
        <view class="card-header">
          <view class="card-header-left">
            <text class="cuIcon-myfill"></text>
            <text class="card-title">我的账户</text>
          </view>
          <text class="card-tag">已缴费用</text>
        </view>
        
        <!-- 添加标签页说明 -->
        <view v-if="activeTab === 2 || activeTab === 3" class="tab-notice">
          <text class="notice-text">门禁卡和人脸只支持运维费续费</text>
        </view>

        <view class="card-content">
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-state">
            <text class="loading-text">加载中...</text>
          </view>
          
          <!-- 错误信息 -->
          <view v-else-if="error" class="error-state">
            <text class="error-text">{{ error }}</text>
            <view class="error-actions">
              <button class="retry-btn" @click="fetchHouseList">刷新数据</button>
              <button v-if="error.includes('创建订单')" class="retry-btn" @click="retryCreateMergeOrder">重试创建订单</button>
            </view>
          </view>
          
          <!-- 数据内容 -->
          <view v-else-if="filteredAccountData.length">
            <view v-for="(item, idx) in filteredAccountData" :key="item.id"
              :class="['account-card-box', { 'selected': selectedIds.includes(item.id) }]"
              @click="toggleSelect(item.id)">
              <view class="account-card-flex">
                <!-- 去掉checkbox -->
                <view class="account-card-info">
                  <view class="account-card-title-row">
                    <view class="account-card-title">
                      {{ item.address || item.door || '-' }}
                      <text v-if="item.balance < 0" class="status-tag overdue">欠费</text>
                      <text v-else-if="item.balance === 0" class="status-tag normal">正常</text>
                      <text v-else class="status-tag surplus">余额</text>
                    </view>
                    <view class="account-card-amount">¥{{ item.totalPrice !== undefined ? (Number(item.totalPrice)).toFixed(2) : '-' }}</view>
                  </view>
                  <view class="account-card-sub-row">
                    <text>房东手机号：{{ item.landlordPhone || '-' }}</text>
                    <text style="margin-left: 24rpx;">月费：¥{{ item.monthPrice || '-' }}</text>
                  </view>
                  <view class="account-card-sub-row">
                    <text v-if="item.balance < 0" class="balance-text overdue">欠费：¥{{ Math.abs(item.balance) }}</text>
                    <text v-else-if="item.balance === 0" class="balance-text normal">余额：¥0.00</text>
                    <text v-else class="balance-text surplus">余额：¥{{ item.balance }}</text>
                  </view>
                  <view class="account-card-sub-row">
                    <text>服务期：{{ item.startDate || '-' }} 至 {{ item.endDate || '-' }}</text>
                  </view>
                  <view class="account-card-sub-row">
                    <text>地址：{{ formatAddress(item) }}</text>
                  </view>
                </view>
                <button 
                  class="pay-btn-card" 
                  :class="getButtonClass(item)"
                  @click.stop="goPay(item)"
                >
                  {{ getButtonText(item) }}
                </button>
              </view>
            </view>
          </view>
          
          <!-- 空数据状态 -->
          <view v-else class="empty-data">
            <text>暂无数据</text>
          </view>
        </view>
      </view>

      <!-- 优惠信息 -->
      <view class="coupon-section">
        <view class="coupon-icon">
          <text class="cuIcon-ticket"></text>
        </view>
        <view class="coupon-text">一次性缴费12个月送2个月使用时长</view>
        <view class="coupon-more" @click="showCouponDetails">
          <text>详情</text>
          <text class="iconfont icon-right"></text>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="footer-section">
      <view class="checkout-bar">
        <!-- 移除全选 -->
        <view class="total-price">
          <text>合计:</text>
          <text class="price">¥{{ totalSelectedPrice }}</text>
        </view>
        <view class="checkout-btn2" :class="{disabled: !selectedIds.length}" @click="selectedIds.length ? payNow() : null">合并缴费</view>
      </view>
    </view>

    <!-- 年限选择弹窗 -->
    <uni-popup ref="durationPopup" type="bottom">
      <view class="duration-popup">
        <view class="popup-header">
          <text class="popup-title">选择缴费年限</text>
          <text class="close-btn" @click="closeDurationPopup">×</text>
        </view>
        <view class="duration-list">
          <view v-for="option in durationOptions" :key="option.years" 
                :class="['duration-option', { 'selected': selectedDuration === option.years && !customMonths }]" 
                @click="selectDuration(option)">
            <view class="duration-info">
              <text class="duration-title">{{ option.label }}</text>
              <text class="duration-desc">{{ option.desc }}</text>
            </view>
            <text class="duration-price">¥{{ calculateDurationPrice(option.years) }}</text>
          </view>
          
          <!-- 自定义月数选项 -->
          <view class="custom-duration-section">
            <view class="custom-duration-header">
              <text class="custom-duration-title">自定义缴费月数</text>
            </view>
            <view class="custom-duration-input-row">
              <view class="input-wrapper">
                <input 
                  type="number" 
                  v-model="customMonths" 
                  placeholder="请输入月数" 
                  class="custom-months-input"
                  @input="onCustomMonthsInput"
                  @blur="validateCustomMonths"
                />
                <text class="input-suffix">个月</text>
              </view>
              <view class="custom-price-display">
                <text class="custom-price">¥{{ calculateCustomMonthsPrice() }}</text>
              </view>
            </view>
            <view class="custom-duration-tips">
              <text class="tips-text">建议缴费1-36个月，一次性缴费12个月送2个月</text>
              <text class="tips-text">输入月数后，点击底部"合并缴费"按钮完成支付</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getHouseList } from '@/api/door/house';
import { addOrderInfo } from '@/api/login';
export default {
  data() {
    return {
      accountData: [],
      userInfo: {
        avatar: '',
        name: '',
        phone: ''
      },
      selectedIds: [],
      activeTab: 1, // 默认运维费
      loading: false, // 添加加载状态
      error: '', // 添加错误信息
      // 年限选择相关
      currentPaymentItem: null, // 当前要缴费的项目
      currentPaymentType: 'single', // single: 单个缴费, merge: 合并缴费
      selectedDuration: 1, // 选择的缴费年限
      durationOptions: [
        { years: 1, label: '1年', desc: '按年缴费，灵活续费' },
        { years: 2, label: '2年', desc: '两年优惠，省心省力' },
        { years: 3, label: '3年', desc: '三年优惠，超值套餐' }
      ],
      // 自定义月数相关
      customMonths: '', // 自定义缴费月数
      isCustomPayment: false, // 是否使用自定义月数缴费
      isPopupOpened: false, // 弹窗是否已打开
    }
  },
  computed: {
    tabs() {
      return [
      ];
    },
    filteredAccountData() {
      // 门禁卡和人脸只显示运维费续费数据
      if (this.activeTab === 2 || this.activeTab === 3) {
        return this.accountData.filter(item => item.type === 1); // 只显示运维费
      }
      return this.accountData.filter(item => item.type === this.activeTab);
    },
    totalSelectedPrice() {
      // 根据用户选择的年限或自定义月数计算实际缴费金额
      const selected = this.filteredAccountData.filter(item => this.selectedIds.includes(item.id));
      
      if (selected.length === 0) {
        return '0.00';
      }
      
      // 计算总月费
      const totalMonthPrice = selected.reduce((sum, item) => sum + (item.monthPrice || 0), 0);
      
      // 根据用户选择计算实际缴费金额
      if (this.customMonths && this.isCustomMonthsValid) {
        // 使用自定义月数
        const months = parseInt(this.customMonths);
        return (totalMonthPrice * months).toFixed(2);
      } else if (this.selectedDuration && this.selectedDuration > 0) {
        // 使用选择的年限
        return (totalMonthPrice * 12 * this.selectedDuration).toFixed(2);
      } else {
        // 默认1年
        return (totalMonthPrice * 12).toFixed(2);
      }
    },
    isAllSelected() {
      const ids = this.filteredAccountData.map(item => item.id);
      return ids.length > 0 && ids.every(id => this.selectedIds.includes(id));
    },
    // 验证自定义月数是否有效
    isCustomMonthsValid() {
      const months = parseInt(this.customMonths);
      return !isNaN(months) && months >= 1 && months <= 36;
    }
  },
  created() {
    // 获取用户数据
    const userStore = this.$store.state.user;
    if (userStore) {
      this.userInfo.avatar = userStore.avatar || '';
      this.userInfo.name = userStore.name || '';
      // 从store中获取用户名作为手机号，或者从storage中获取
      this.userInfo.phone = userStore.name || '';
    }
    
    // 如果store中没有手机号，尝试从storage中获取
    if (!this.userInfo.phone) {
      const storage = uni.getStorageSync('userInfo');
      if (storage && storage.username) {
        this.userInfo.phone = storage.username;
      }
    }
    
    // 如果还是没有手机号，使用默认值（开发测试用）
    if (!this.userInfo.phone) {
      this.userInfo.phone = '18612511092'; // 默认手机号，实际使用时应该从登录信息获取
    }
    
    this.fetchHouseList();
  },
  methods: {
    async fetchHouseList() {
      try {
        this.loading = true;
        this.error = '';
        
        // 使用新的接口获取房产列表
        const params = {
          pageNum: 1,
          pageSize: 100, // 获取更多数据
          landlordPhone: this.userInfo.phone
        };
        
        console.log('获取房产列表参数:', params);
        console.log('当前用户手机号:', this.userInfo.phone);
        
        const res = await getHouseList(params);
        console.log('房产列表接口返回:', res);
        
        if (res.code === 200 && res.rows) {
          // 根据新的接口返回值转换数据
          this.accountData = res.rows.map(item => ({
            id: item.id,
            address: item.address || item.door || '-',
            door: item.door,
            monthPrice: item.monthPrice || 0,
            startDate: item.startDate,
            endDate: item.endDate,
            landlordName: item.landlordName,
            landlordPhone: item.landlordPhone,
            balance: item.balance || 0,
            // 地址信息
            countryName: item.countryName,
            provinceName: item.provinceName,
            cityName: item.cityName,
            districtName: item.districtName,
            streetName: item.streetName,
            villageName: item.villageName,
            // 计算费用信息
            totalPrice: Math.abs(item.balance || 0), // 欠费金额
            unitPrice: item.monthPrice || 0, // 月费用
            buyCount: 1,
            createTime: item.createTime || new Date().toISOString(),
            type: 1, // 统一设置为运维费类型
            // 保留原始房产信息
            ...item
          }));
          
          console.log('转换后的账户数据:', this.accountData);
        } else {
          this.accountData = [];
          this.error = res.msg || '获取数据失败';
          console.log('房产列表接口返回异常:', res);
        }
      } catch (e) {
        console.error('获取房产列表失败:', e);
        this.accountData = [];
        this.error = '网络请求失败，请检查网络连接';
      } finally {
        this.loading = false;
      }
    },
    goPay(item) {
      // 单个缴费：先选中该项目，然后打开年限选择弹窗
      this.currentPaymentItem = item;
      this.currentPaymentType = 'single';
      this.selectedDuration = 1;
      
      // 自动选中当前项目
      this.selectedIds = [item.id];
      
      // 重置自定义月数，让用户重新选择
      this.customMonths = '';
      this.isCustomPayment = false;
      
      this.$refs.durationPopup.open();
      this.isPopupOpened = true;
    },
    handleToLogin() {
      // 切换账号逻辑
      uni.navigateTo({
        url: '/pages/login'
      });
    },
    payNow() {
      // 缴费逻辑
      if (!this.selectedIds.length) {
        uni.showToast({ title: '请先选择要缴费的订单', icon: 'none' });
        return;
      }
      
      console.log('payNow called, customMonths:', this.customMonths, 'isCustomMonthsValid:', this.isCustomMonthsValid);
      
      // 如果弹窗已经打开且用户已做出选择（自定义月数或预设年限），直接执行缴费
      // 使用一个标志来跟踪弹窗状态
      if (this.isPopupOpened && ((this.customMonths && this.isCustomMonthsValid) || (this.selectedDuration && this.selectedDuration > 0))) {
        // 根据实际情况判断是否使用自定义月数
        this.isCustomPayment = !!(this.customMonths && this.isCustomMonthsValid);
        
        // 确定缴费类型
        if (this.selectedIds.length === 1 && this.currentPaymentItem) {
          this.currentPaymentType = 'single';
        } else {
          this.currentPaymentType = 'merge';
        }
        
        this.$refs.durationPopup.close();
        this.isPopupOpened = false;
        
        console.log('Executing payment with type:', this.currentPaymentType);
        
        // 根据缴费类型执行相应的缴费逻辑
        if (this.currentPaymentType === 'single') {
          this.executeSinglePayment();
        } else {
          this.executeMergePayment();
        }
        return;
      }
      
      // 打开年限选择弹窗（每次打开时重置状态）
      if (!this.currentPaymentType) {
        this.currentPaymentType = 'merge';
      }
      this.selectedDuration = 1;
      // 重置自定义月数，让用户重新选择
      this.customMonths = '';
      this.isCustomPayment = false;
      this.$refs.durationPopup.open();
      this.isPopupOpened = true;
    },
    showCouponDetails() {
      // 显示优惠信息详情
      uni.showModal({
        title: '优惠详情',
        content: '一次性缴费12个月可免费获赠2个月使用时长，共计14个月服务期。',
        showCancel: false,
        confirmText: '我知道了'
      });
    },
    // 多选切换
    toggleSelect(id) {
      const idx = this.selectedIds.indexOf(id);
      if (idx > -1) {
        this.selectedIds.splice(idx, 1);
      } else {
        this.selectedIds.push(id);
      }
    },
    // 全选/取消全选
    toggleSelectAll() {
      const ids = this.filteredAccountData.map(item => item.id);
      if (this.isAllSelected) {
        this.selectedIds = this.selectedIds.filter(id => !ids.includes(id));
      } else {
        this.selectedIds = Array.from(new Set([...this.selectedIds, ...ids]));
      }
    },
    
    // 格式化地址
    formatAddress(item) {
      const addressParts = [];
      if (item.provinceName) addressParts.push(item.provinceName);
      if (item.cityName) addressParts.push(item.cityName);
      if (item.districtName) addressParts.push(item.districtName);
      if (item.streetName) addressParts.push(item.streetName);
      if (item.villageName) addressParts.push(item.villageName);
      return addressParts.length > 0 ? addressParts.join('') : '暂无地址信息';
    },
    
    // 重试创建订单
    async retryCreateOrder(item) {
      await this.goPay(item);
    },
    
    // 重试创建合并订单
    async retryCreateMergeOrder() {
      await this.payNow();
    },
    
    getButtonText(item) {
      if (item.balance < 0) {
        return '去缴费';
      } else if (item.balance === 0) {
        return '续费';
      } else {
        return '查看';
      }
    },
    getButtonClass(item) {
      if (item.balance < 0) {
        return 'pay-btn-card-overdue';
      } else if (item.balance === 0) {
        return 'pay-btn-card-normal';
      } else {
        return 'pay-btn-card-surplus';
      }
    },
    
    // 年限选择相关方法
    calculateDurationPrice(years) {
      // 计算指定年限的费用
      // 优先检查是否有选中的项目来计算价格
      const selectedItems = this.filteredAccountData.filter(item => this.selectedIds.includes(item.id));
      
      console.log('calculateDurationPrice called:', {
        years,
        selectedItemsCount: selectedItems.length,
        currentPaymentItem: this.currentPaymentItem,
        selectedIds: this.selectedIds
      });
      
      if (selectedItems.length > 0) {
        // 根据选中的项目计算总月费
        const totalMonthPrice = selectedItems.reduce((sum, item) => sum + (item.monthPrice || 0), 0);
        const result = (totalMonthPrice * 12 * years).toFixed(2);
        console.log('Selected items price calculation:', { totalMonthPrice, result });
        return result;
      } else if (this.currentPaymentItem) {
        // 单个缴费情况
        const result = (this.currentPaymentItem.monthPrice * 12 * years).toFixed(2);
        console.log('Single item price calculation:', { 
          monthPrice: this.currentPaymentItem.monthPrice, 
          result 
        });
        return result;
      }
      
      console.log('No items found, returning 0.00');
      return '0.00';
    },
    
    closeDurationPopup() {
      this.$refs.durationPopup.close();
      // 不要重置 currentPaymentItem，因为价格计算需要用到
      // this.currentPaymentItem = null;
      this.currentPaymentType = 'single';
      this.selectedDuration = 1;
      this.customMonths = '';
      this.isCustomPayment = false;
      this.isPopupOpened = false;
    },
    
    selectDuration(option) {
      this.selectedDuration = option.years;
      this.isCustomPayment = false;
      // 清空自定义月数，因为用户选择了预设年限
      this.customMonths = '';
      
      console.log('Selected duration:', option.years, 'years');
      
      // 不要立即关闭弹窗，让用户看到合计金额更新
      // 用户需要点击底部的"合并缴费"按钮来完成支付
    },
    
    // 自定义月数相关方法
    onCustomMonthsInput(e) {
      this.customMonths = e.detail.value;
      // 当用户输入自定义月数时，清空预设年限选择
      if (this.customMonths) {
        this.selectedDuration = 0; // 设置为0表示没有选择预设年限
      }
      console.log('Custom months input:', this.customMonths, 'Valid:', this.isCustomMonthsValid);
    },
    
    validateCustomMonths() {
      const months = parseInt(this.customMonths);
      if (isNaN(months) || months < 1 || months > 36) {
        uni.showToast({
          title: '请输入1-36之间的月数',
          icon: 'none'
        });
      }
    },
    
    calculateCustomMonthsPrice() {
      if (!this.isCustomMonthsValid) {
        return '0.00';
      }
      
      const months = parseInt(this.customMonths);
      
      // 优先检查是否有选中的项目来计算价格
      const selectedItems = this.filteredAccountData.filter(item => this.selectedIds.includes(item.id));
      
      if (selectedItems.length > 0) {
        // 根据选中的项目计算总月费
        const totalMonthPrice = selectedItems.reduce((sum, item) => sum + (item.monthPrice || 0), 0);
        return (totalMonthPrice * months).toFixed(2);
      } else if (this.currentPaymentItem) {
        // 单个缴费情况
        return (this.currentPaymentItem.monthPrice * months).toFixed(2);
      }
      
      return '0.00';
    },
    
    
    async executeSinglePayment() {
      if (!this.currentPaymentItem) return;
      
      const item = this.currentPaymentItem;
      
      try {
        this.loading = true;
        this.error = '';

        // 计算实际缴费月数
        let actualMonths;
        if (this.isCustomPayment) {
          actualMonths = parseInt(this.customMonths);
          if (isNaN(actualMonths) || actualMonths < 1) {
            uni.showToast({ title: '请输入有效的缴费月数', icon: 'none' });
            this.loading = false;
            return;
          }
        } else {
          actualMonths = (this.selectedDuration || 1) * 12;
        }
        
        // 构建订单详情列表
        const orderDetailList = [{
          address: item.address || item.door || '',
          buyCount: actualMonths, // 使用实际月数
          city: item.city || 0,
          country: item.country || 0,
          deptId: item.deptId || 0,
          district: item.district || 0,
          door: item.door || '',
          houseId: item.id || 0,
          isPolice: '0',
          name: item.landlordName || this.userInfo.name || '',
          phone: item.landlordPhone || this.userInfo.phone || '',
          province: item.province || 0,
          street: item.street || 0,
          unitPrice: item.monthPrice * actualMonths || 0, // 使用实际月数计算总价
          village: item.village || 0,
          type: 1 // 运维费类型
        }];

        // 创建订单信息
        const orderParams = {
          chCardNo: '',
          chIdNo: '',
          chMobile: item.landlordPhone || this.userInfo.phone || '',
          openid: uni.getStorageSync('wechat_openid'),
          chName: item.landlordName || this.userInfo.name || '',
          landlordName: item.landlordName || this.userInfo.name || '',
          landlordPhone: item.landlordPhone || this.userInfo.phone || '',
          orderDetailList: orderDetailList,
          payChannel: '1', // 微信支付
          protocolNo: '',
          remark: `房产：${item.address || item.door || ''}，房东：${item.landlordName || ''}，运维费续费${actualMonths}个月`,
          type: 1 // 运维费类型
        };

        console.log('创建订单参数:', orderParams);

        const res = await addOrderInfo(orderParams);
        console.log('创建订单接口返回:', res);

        if (res.code === 200 && res.data) {
          // 合并房产信息到订单对象
          const orderData = {
            ...res.data,
            // 保留房产信息
            houseId: item.id,
            address: item.address || item.door || '',
            door: item.door || '',
            monthPrice: item.monthPrice || 0,
            startDate: item.startDate,
            endDate: item.endDate,
            landlordName: item.landlordName || '',
            landlordPhone: item.landlordPhone || '',
            balance: item.balance || 0,
            selectedDuration: this.isCustomPayment ? `${actualMonths}个月` : `${this.selectedDuration}年`,
            actualMonths: actualMonths,
            // 地址信息
            countryName: item.countryName,
            provinceName: item.provinceName,
            cityName: item.cityName,
            districtName: item.districtName,
            streetName: item.streetName,
            villageName: item.villageName
          };

          // 跳转到确认缴费页面，带上订单信息
          uni.navigateTo({
            url: `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(orderData))}&payType=wx`
          });
        } else {
          this.error = res.msg || '创建订单失败';
          console.log('创建订单接口返回异常:', res);
        }
      } catch (e) {
        console.error('创建订单失败:', e);
        this.error = '网络请求失败，请检查网络连接';
      } finally {
        this.loading = false;
        this.currentPaymentItem = null;
      }
    },
    
    async executeMergePayment() {
      try {
        this.loading = true;
        this.error = '';
        
        // 根据当前标签页获取选中的项目
        const selectedItems = this.filteredAccountData.filter(item => this.selectedIds.includes(item.id));
        
        if (selectedItems.length === 0) {
          uni.showToast({ title: '没有选中的缴费项目', icon: 'none' });
          return;
        }
        
        // 计算实际缴费月数
        let actualMonths;
        if (this.isCustomPayment) {
          actualMonths = parseInt(this.customMonths);
          if (isNaN(actualMonths) || actualMonths < 1) {
            uni.showToast({ title: '请输入有效的缴费月数', icon: 'none' });
            this.loading = false;
            return;
          }
        } else {
          actualMonths = (this.selectedDuration || 1) * 12;
        }
        
        // 构建订单详情列表
        const orderDetailList = selectedItems.map(item => ({
          address: item.address || item.door || '',
          buyCount: actualMonths, // 使用实际月数
          city: item.city || 0,
          country: item.country || 0,
          deptId: item.deptId || 0,
          district: item.district || 0,
          door: item.door || '',
          houseId: item.id || 0,
          isPolice: '0',
          name: item.landlordName || this.userInfo.name || '',
          phone: item.landlordPhone || this.userInfo.phone || '',
          province: item.province || 0,
          street: item.street || 0,
          unitPrice: item.monthPrice * actualMonths || 0, // 使用实际月数计算总价
          village: item.village || 0,
          type: 1 // 运维费类型
        }));

        // 创建合并订单
        const orderParams = {
          chCardNo: '',
          chIdNo: '',
          chMobile: this.userInfo.phone || '',
          chName: this.userInfo.name || '',
          landlordName: this.userInfo.name || '',
          landlordPhone: this.userInfo.phone || '',
          orderDetailList: orderDetailList,
          openid: uni.getStorageSync('wechat_openid'),
          payChannel: '1', // 微信支付
          protocolNo: '',
          remark: `合并缴费：共${selectedItems.length}个房产，运维费续费${actualMonths}个月`,
          type: 1 // 运维费类型
        };

        console.log('创建合并订单参数:', orderParams);

        const res = await addOrderInfo(orderParams);
        console.log('创建合并订单接口返回:', res);

        if (res.code === 200 && res.data) {
          // 合并房产信息到订单对象
          const orderData = {
            ...res.data,
            // 保留选中的房产信息
            selectedItems: selectedItems,
            totalAmount: this.calculateDurationPrice(this.selectedDuration),
            itemCount: selectedItems.length,
            selectedDuration: this.isCustomPayment ? `${actualMonths}个月` : `${this.selectedDuration}年`,
            actualMonths: actualMonths
          };

          // 跳转到确认缴费页面
          uni.navigateTo({
            url: `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(orderData))}&payType=wx`,
            fail: (err) => {
              uni.showToast({ title: '跳转失败：' + JSON.stringify(err), icon: 'none' });
            }
          });
        } else {
          this.error = res.msg || '创建合并订单失败';
          uni.showToast({ title: res.msg || '创建订单失败', icon: 'none' });
        }
      } catch (e) {
        console.error('创建合并订单失败:', e);
        this.error = '网络请求失败，请检查网络连接';
        uni.showToast({ title: '创建订单失败，请重试', icon: 'none' });
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.account-container {
  min-height: 100vh;
  background-color: #f5f6f7;
  display: flex;
  flex-direction: column;
  position: relative;
}

// 顶部用户信息区域
.user-info-section {
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  background-color: #fff;
  position: relative;
  
  .user-avatar-wrapper {
    width: 120rpx;
    height: 120rpx;
    margin-right: 20rpx;
    
    .user-avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      
      .icon {
        font-size: 60rpx;
      }
    }
  }
  
  .user-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .user-phone {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .user-phone-sub {
      font-size: 30rpx;
      color: #666;
    }
  }
  
  .switch-account {
    color: #3c96f3;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    
    .icon-right {
      font-size: 24rpx;
      margin-left: 4rpx;
    }
  }
}

// 主要内容区域
.main-content {
  flex: 1;
  padding-bottom: 100rpx;
  overflow-y: auto;
}

// 账户卡片
.account-card {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
  
  .card-header {
    padding: 20rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    
    .card-header-left {
      display: flex;
      align-items: center;
      
      .cuIcon-myfill {
        color: #3c96f3;
        font-size: 40rpx;
        margin-right: 10rpx;
      }
      
      .card-title {
        font-size: 32rpx;
        font-weight: bold;
      }
    }
    
    .card-tag {
      background-color: #3c96f3;
      color: #fff;
      padding: 4rpx 20rpx;
      border-radius: 30rpx;
      font-size: 24rpx;
    }
  }
  
  // 标签页说明样式
  .tab-notice {
    padding: 16rpx 30rpx;
    background-color: #fff7e6;
    border-bottom: 1px solid #f0f0f0;
    
    .notice-text {
      color: #ff7a45;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      
      &::before {
        content: "ℹ";
        margin-right: 8rpx;
        font-weight: bold;
      }
    }
  }

  .card-content {
    padding: 20rpx 0;
    
    .table-header {
      display: flex;
      padding: 0 20rpx;
      
      .col {
        flex: 1;
        text-align: center;
        font-size: 28rpx;
        color: #333;
        padding: 16rpx 0;
      }
    }
    
    .empty-data {
      height: 200rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #999;
      font-size: 28rpx;
    }
    
    // 加载状态样式
    .loading-state {
      height: 200rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      
      .loading-text {
        color: #666;
        font-size: 28rpx;
      }
    }
    
    // 错误状态样式
    .error-state {
      height: 200rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      
      .error-text {
        color: #f56c6c;
        font-size: 28rpx;
        margin-bottom: 20rpx;
        text-align: center;
      }
      
      .error-actions {
        display: flex;
        gap: 20rpx;
        justify-content: center;
        margin-top: 20rpx;
      }
      
      .retry-btn {
        background: #3c96f3;
        color: #fff;
        border: none;
        border-radius: 24rpx;
        font-size: 24rpx;
        padding: 12rpx 32rpx;
        min-width: 120rpx;
      }
    }
    
    .no-data-tip {
      text-align: center;
      padding: 20rpx 0;
      color: #999;
      font-size: 28rpx;
    }
  }
}

// 账户明细卡片样式
.account-detail-card {
  background: #f7f8fa;
  border-radius: 16rpx;
  margin: 20rpx 0;
  padding: 24rpx 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  .card-row {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;
    .label {
      color: #888;
      font-size: 26rpx;
      min-width: 140rpx;
    }
    .value {
      color: #222;
      font-size: 28rpx;
      font-weight: 500;
    }
    &.card-action {
      justify-content: flex-end;
      margin-top: 10rpx;
      margin-bottom: 0;
    }
  }
}

// 优惠信息区域
.coupon-section {
  background-color: #fff9f5;
  margin: 20rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  border-radius: 12rpx;
  
  .coupon-icon {
    margin-right: 20rpx;
    
    .cuIcon-ticket {
      color: #ff7a45;
      font-size: 40rpx;
    }
  }
  
  .coupon-text {
    flex: 1;
    font-size: 26rpx;
    color: #ff7a45;
  }
  
  .coupon-more {
    color: #999;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    
    .icon-right {
      margin-left: 4rpx;
    }
  }
}

// 底部结算栏
.footer-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
  
  .checkout-bar {
    padding: 20rpx 30rpx;
    display: flex;
    align-items: center;
    
    .checkout-select {
      display: flex;
      align-items: center;
      margin-right: 30rpx;
      
      .select-all {
        transform: scale(0.8);
        margin-right: 10rpx;
      }
    }
    
    .total-price {
      flex: 1;
      display: flex;
      align-items: center;
      
      .price {
        color: #f56c6c;
        font-size: 36rpx;
        font-weight: bold;
        margin-left: 10rpx;
      }
    }
    
    .checkout-btn {
      background-color: #3c96f3;
      color: #fff;
      padding: 16rpx 40rpx;
      border-radius: 50rpx;
      font-size: 28rpx;
    }
  }
}

// 添加安全区域适配
@media screen and (min-width: 768px) {
  .footer-section {
    padding-bottom: env(safe-area-inset-bottom);
  }
}

.table-header, .table-row {
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}
.table-header {
  background: #f7f8fa;
  font-weight: bold;
  color: #333;
  font-size: 28rpx;
  border-bottom: 1px solid #f0f0f0;
}
.table-row {
  border-bottom: 1px solid #f0f0f0;
  font-size: 26rpx;
  color: #222;
  min-height: 80rpx;
}
.col {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.pay-btn-mini {
  background: linear-gradient(90deg, #07c160 0%, #34d399 100%);
  color: #fff;
  border: none;
  border-radius: 32rpx;
  font-size: 24rpx;
  padding: 8rpx 24rpx;
  margin: 0 auto;
  display: inline-block;
}
// 卡片风格+多选
.account-card-box {
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(60,150,243,0.15);
  border: 2rpx solid #f0f3f8;
  margin-bottom: 32rpx;
  margin-left: 12rpx;
  margin-right: 12rpx;
  padding: 0;
  overflow: hidden;
  transition: box-shadow 0.2s, border-color 0.2s, background 0.2s;
}
.account-card-box.selected {
  border-color: #3c96f3;
  background: #f0f7ff;
  box-shadow: 0 12rpx 36rpx rgba(60,150,243,0.22);
}
.account-card-flex {
  display: flex;
  align-items: center;
  padding: 18rpx 18rpx 18rpx 12rpx;
}
.card-checkbox {
  margin-right: 18rpx;
  transform: scale(0.9);
}
.account-card-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}
.account-card-title-row {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin-bottom: 6rpx;
}
.account-card-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #222;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
  
  .status-tag {
    font-size: 20rpx;
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
    margin-left: 12rpx;
    font-weight: normal;
    
    &.overdue {
      background: #fff2f0;
      color: #f56c6c;
      border: 1rpx solid #ffccc7;
    }
    
    &.normal {
      background: #f6ffed;
      color: #52c41a;
      border: 1rpx solid #b7eb8f;
    }
    
    &.surplus {
      background: #e6f7ff;
      color: #1890ff;
      border: 1rpx solid #91d5ff;
    }
  }
}
.account-card-amount {
  font-size: 26rpx;
  font-weight: 600;
  color: #3c96f3;
  margin-left: 12rpx;
  white-space: nowrap;
}
.account-card-sub-row {
  font-size: 22rpx;
  color: #888;
  margin-bottom: 2rpx;
  display: flex;
  align-items: center;
  
  .balance-text {
    font-weight: 600;
    
    &.overdue {
      color: #f56c6c;
    }
    
    &.normal {
      color: #52c41a;
    }
    
    &.surplus {
      color: #1890ff;
    }
  }
}
.pay-btn-card {
  background: linear-gradient(90deg, #3c96f3 0%, #5ad1ff 100%);
  color: #fff;
  border: none;
  border-radius: 32rpx;
  font-size: 24rpx;
  padding: 12rpx 36rpx;
  font-weight: 600;
  margin-left: 18rpx;
  box-shadow: 0 4rpx 16rpx rgba(60,150,243,0.18);
  white-space: nowrap;
  transition: background 0.2s;
  
  &.pay-btn-card-overdue {
    background: linear-gradient(90deg, #f56c6c 0%, #ff7875 100%);
    box-shadow: 0 4rpx 16rpx rgba(245,108,108,0.18);
  }
  
  &.pay-btn-card-normal {
    background: linear-gradient(90deg, #52c41a 0%, #73d13d 100%);
    box-shadow: 0 4rpx 16rpx rgba(82,196,26,0.18);
  }
  
  &.pay-btn-card-surplus {
    background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%);
    box-shadow: 0 4rpx 16rpx rgba(24,144,255,0.18);
  }
}
.pay-btn-card:active {
  background: linear-gradient(90deg, #2b7fd6 0%, #3c96f3 100%);
}
.checkout-btn2 {
  background: #3c96f3;
  color: #fff;
  border-radius: 32rpx;
  font-size: 26rpx;
  padding: 12rpx 44rpx;
  font-weight: 600;
  margin-left: 18rpx;
  transition: opacity 0.2s;
}
.checkout-btn2.disabled {
  opacity: 0.5;
}
.account-tabs {
  display: flex;
  background: #fff;
  border-bottom: 1px solid #eee;
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 30rpx;
    color: #888;
    position: relative;
    cursor: pointer;
  }
  .tab-item.active {
    color: #3c96f3;
    font-weight: bold;
    border-bottom: 4rpx solid #3c96f3;
  }
}

// 年限选择弹窗样式
.duration-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
  overflow-y: auto;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 40rpx 24rpx 40rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .close-btn {
      font-size: 40rpx;
      color: #999;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: #f5f5f5;
      cursor: pointer;
      
      &:active {
        background: #e5e5e5;
      }
    }
  }
  
  .duration-list {
    padding: 24rpx 40rpx 40rpx 40rpx;
    max-height: calc(80vh - 120rpx);
    overflow-y: auto;
    
    .duration-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx 24rpx;
      margin-bottom: 16rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
      border: 2rpx solid transparent;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: #e6f3ff;
        border-color: #3c96f3;
      }
      
      &:active {
        transform: scale(0.98);
      }
      
      &:last-child {
        margin-bottom: 0;
      }
      
      &.selected {
        background: #e6f3ff;
        border-color: #3c96f3;
        box-shadow: 0 2rpx 8rpx rgba(60,150,243,0.2);
      }
      
      .duration-info {
        flex: 1;
        
        .duration-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }
        
        .duration-desc {
          font-size: 26rpx;
          color: #666;
          display: block;
        }
      }
      
      .duration-price {
        font-size: 34rpx;
        font-weight: 700;
        color: #3c96f3;
        margin-left: 24rpx;
      }
    }
  }
  
  // 自定义月数区域样式
  .custom-duration-section {
    margin-top: 24rpx;
    padding: 24rpx 0;
    border-top: 2px solid #e6f3ff;
    background: #fafcff;
    
    .custom-duration-header {
      margin-bottom: 24rpx;
      
      .custom-duration-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .custom-duration-input-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16rpx;
      
      .input-wrapper {
        flex: 1;
        display: flex;
        align-items: center;
        background: #f8f9fa;
        border-radius: 12rpx;
        padding: 0 20rpx;
        border: 2rpx solid transparent;
        transition: border-color 0.3s;
        
        &:focus-within {
          border-color: #3c96f3;
          background: #fff;
        }
        
        .custom-months-input {
          flex: 1;
          height: 80rpx;
          font-size: 28rpx;
          color: #333;
          background: transparent;
          border: none;
          outline: none;
        }
        
        .input-suffix {
          font-size: 26rpx;
          color: #666;
          margin-left: 8rpx;
        }
      }
      
      .custom-price-display {
        margin-left: 24rpx;
        
        .custom-price {
          font-size: 32rpx;
          font-weight: 700;
          color: #3c96f3;
        }
      }
    }
    
    .custom-duration-tips {
      margin-bottom: 0;
      
      .tips-text {
        font-size: 24rpx;
        color: #999;
        line-height: 1.4;
        display: block;
        margin-bottom: 8rpx;
        
        &:last-child {
          margin-bottom: 0;
          color: #3c96f3;
          font-weight: 500;
        }
      }
    }
  }
}
</style> 